use "$datapath/A3_age55data_WC_rdrobust.dta",clear


{ // Indicate first observations of new job
*===============================================================================
*Condtion on newfirm==1 and observred wage (post eventtime>=0 by construction)
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid) if newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate) // impute for all obs this value
format nvalsdate %tm

/*
*Generte same as above but correct for observing the wage possibly earlier
bys lopnr (eventtime) : gen nvals2 = sum(1) if firmid_lonestruktur==firstnewfirmid & eventtime_def>=0 & firmid_lonestruktur!=.
gen xnvals2date = date if nvals2==1 
bys lopnr (eventtime_def) : egen nvals2date = max(xnvals2date) // impute for all obs this value
format nvals2date %tm

*Indicate first wage from new firm in wage survey (no matter the firm and RAMS indicators)
bys lopnr (eventtime) : gen nvals4 = sum(1) if firmid!=firmid_lonestruktur & firmid_lonestruktur!=. & eventtime_def>=0
*/


*Pre wage from notifying firm (last observred wage at notifying firm before or at notification)
bys lopnr (eventtime_def) : gen nvals3 = _n if manl!=. & date<=nvalsdate & eventtime_def<=0
bys lopnr (eventtime_def) : egen maxnvals3 = max(nvals3)


*Date for last wage at notifying firm (within 2 yers before notification)
gen xnvals3date = date if nvals3==maxnvals3	& nvals3!=. & inrange(eventtime_def,-24,0)
bys lopnr (eventtime_def) : egen nvals3date = max(xnvals3date)
format nvals3date %tm

*Difference in time between old and new wage
gen diff = nvalsdate - nvals3date
sum diff if nvals==1

*Wage at notifying firm	
gen xprewage = manl if date==nvals3date 
bys lopnr (eventtime_def) : egen prenotfwage = max(xprewage)
drop xprewage

*fixa sa att datumet for gamla lonen inte far vara efter nya jobbet fas (i.e date of nvals3 < date of nvals)

*Generate eventtime for wage growth (i.e time after having found new job)
bys lopnr (eventtime_def) : gen timeafterjob = sum(1) if nvals>=1 & date>= nvalsdate


}
*

{ // Generate wages
*===============================================================================
*Generate log wage variables 
gen log_manl_newfirm = log(manl_newfirm)
bys lopnr (eventtime_def) : gen preobswage= manl_firstnewfirmid[_n-12]!=. & nvals==1 & eventtime_def[_n-12]>=0
bys lopnr (eventtime_def) : replace log_manl_newfirm = log(manl_firstnewfirmid[_n-12]) if preobswage==1
gen diff_log_manl_newfirm = log(manl_newfirm) - log(prenotfwage)
gen log_prenotfwage = log(prenotfwage)

*Generate wage growth per year
gen firstnewwage = manl_newfirm if nvals==1
bys lopnr (eventtime_def) : egen fill_manl_newfirm = max(firstnewwage) 
bys lopnr (eventtime_def) : gen wgrowth = log(manl_newfirm) - log(fill_manl_newfirm)


}
*
*
{ // Generate: Event time to displacement
*===============================================================================
bys lopnr (date) : gen lastmonthwork =  date if  atfirm2[_n-1]==1 & atfirm2==1 & atfirm2[_n+1]==0  & atfirm2[_n+2]==0 
format lastmonthwork %tm

bys lopnr (date) : gen SPnvals = sum(1) 	if lastmonthwork!=.
tab SPnvals 				if lastmonthwork!=.
bys lopnr : egen maxnvals = max(SPnvals)

*Take away displacemnt dates that occur 12 months before notification for those with multiple displacments dates
replace lastmonthwork=. if eventtime_def<-12 & maxnvals>1


bys lopnr (date) : gen SPnvals2 = sum(1) 	if lastmonthwork!=.
tab SPnvals2 				if lastmonthwork!=.
bys lopnr : egen maxnvals2 = max(SPnvals2)
*Now 93.87 percent are displaced only once

 gen SPdiff = lastmonthwork - notdate_def
 tab SPdiff treat 
*So very few do not work 12 months prior to notification so we get rid of these
replace lastmonthwork=. if eventtime_def<-12
drop SPdiff

   
*Taking the minimum date assures that we get the nvals==1 as displacement date
fastmin lastmonthwork , by(lopnr) name(dispdate)
replace dispdate = dispdate +1
format dispdate %tm

*Recalls (working 3 months after displacement event has occured)
bys lopnr (date) : gen xrecalldate = date if atfirm2[_n-2]==0 & atfirm2[_n-1]==0 & atfirm2==1 & atfirm2[_n+1]==1 & atfirm2[_n+3]==1 & date>dispdate
fastmin xrecalldate , by(lopnr) name(recalldate)
format recalldate %tm
drop x*
gen recalled = recalldate!=.   
   
*Generate: Month of displacement
gen monthofdisp = month(dofm(dispdate))

*Generate: Months worked after notification
gen RAMSmonths = dispdate - notdate_def

*Generate: Displacement event time
bys lopnr (date) : gen dispeventtime = date - dispdate

drop SPnvals*
}
*

merge m:1 lopnr year using "$datapath/SP.dta"
drop if _merge==2
drop _merge


{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*

xtset ym_def

gen xlognewwage = log_manl_newfirm if nvals==1 & eventtime_def<=24  
bys lopnr: egen lognewwage = max(xlognewwage)

gen xdifflognewwage = diff_log_manl_newfirm if nvals==1 & eventtime_def<=24   
bys lopnr: egen difflognewwage = max(xdifflognewwage)

gen xSP5 = SP5_win_1_99/1000 if SP5_win_1_99!=. & dispeventtime==0 
bys lopnr: egen maxSP5 = max(xSP5)

gen xannual_tp1 = annual_ear/1000 if eventtime_def==12
bys lopnr : egen annual_tp1 = max(xannual_tp1)

gen nonemp 	= working2==0 
bys lopnr (date) : egen xcumnonemployed 	= total(atfirm2==0 & working2==0) 	if inrange(eventtime_def,1,24) 
bys lopnr : egen cumnonemployed = max(xcumnonemployed)



keep if eventtime_def==0


gen runvar2 = round(runvar*12)


{ // Histogram wage permuation
*===============================================================================
matrix B =J(400,2,.)
xtset ym_def
forvalues b=-60(1)300 {
	local i = `i' + 1
	disp `b'
	gen R = runvar2 + `b'
	gen T = R>0
	gen I = R*T
	
	if `b'==0 {
		xtreg lognewwage		T R I  $covariets	if inrange(R, -36 ,36)  , cluster(varselid) fe nonest 
	}
	else{
		qui xtreg lognewwage		T R I  $covariets	if inrange(R, -36 ,36)  , cluster(varselid) fe nonest 
	}
	matrix B[`i',1] = _b[T]
	matrix B[`i',2] =  `b'
	drop R T I
}	
svmat B

xtreg lognewwage		$instrument $linear $covariets if inrange(runvar,-3,3)  , cluster(varselid) fe nonest 
local trueeffect = round(_b[treat],.001)
twoway 	(hist B1, width(.001) fraction   bcolor(navy%30) ) ///
		(kdensity B1, bwidth(.005) area(0.001)) ///
	,text(.035 .027 "{bf:True}" "{bf:discontinuity}" "{&beta}=0`trueeffect'" "One-sided" "{it:p}-value=0.011", size(small) box bcolor(none)) ///
	graphregion(color(white)) legend(off) xtitle("Estimated ln(wage) effect") ///
	ytitle("Share of estimates") xline(`trueeffect', lcolor(maroon) lpattern(dash))
	
graph export "$agegraphpath/Robust/RDwage_permutation_levelwage_line_300_60_semismooth.pdf",replace	


drop B1 B2
}
*
{ // Histogram SP permuation
*===============================================================================

matrix B =J(400,2,.)
xtset ym_def
forvalues b=-60(1)300 {
	local i = `i' + 1
	disp `b'
	gen R = runvar2 + `b'
	gen T = R>0
	gen I = R*T
	
	if `b'==0 {
		xtreg maxSP5		T R I  $covariets	if inrange(R, -36 ,36)  , cluster(varselid) fe nonest 
	}
	else{
		qui xtreg maxSP5		T R I  $covariets	if inrange(R, -36 ,36)  , cluster(varselid) fe nonest 
	}
	matrix B[`i',1] = _b[T]
	matrix B[`i',2] =  `b'
	drop R T I
}	
svmat B

xtreg maxSP5		$instrument $linear $covariets if inrange(runvar,-3,3)  , cluster(varselid) fe nonest 
local trueeffect = round(_b[treat],.001)
twoway 	(hist B1, width(1) fraction   bcolor(navy%30) ) ///
		(kdensity B1, bwidth(2) area(1)) ///
	,text(.06 13 "{bf:True}" "{bf:discontinuity}" "{&beta}=`trueeffect'" "One-sided" "{it:p}-value=0.014", size(small) box bcolor(none)) ///
	graphregion(color(white)) legend(off) xtitle("Estimated severance effect") ///
	ytitle("Share of estimates") xline(`trueeffect', lcolor(maroon) lpattern(dash))
	
graph export "$agegraphpath/Robust/RDSP_permutation_sp_line_300_60_semismooth.pdf",replace	

}
*



